import { ref } from "vue"
import { getVersion } from '@/config/api.js'
import {
	http
} from '@/config/common.js'
class Upgrade {
    constructor() {
        this.downloadUrl = ''
        this.progress = ref(0)
		this.latestVersion = ''
    }
    getLocalVersion = () => {
        return new Promise((resolve, reject) => {
            plus.runtime.getProperty(plus.runtime.appid, function(widgetInfo) {
                const version = widgetInfo.version
                resolve(version)
            })
        }).catch(err => {
            console.log(err)
        })
    }
    getLatestVersion = () => {
        return new Promise((resolve, reject) => {
            // 相关接口
			getVersion({}).then(res => {
				var data = res.data.data
				this.downloadUrl = data.downloadUrl
				this.latestVersion = data.version
				resolve(this.latestVersion)
			}).catch(err => {
				console.log(err)
			})
        }).catch(err => {
            console.err(err)
        })
    }
    checkVersion = async () => {
        const localVersion = await this.getLocalVersion()
        const latestVersion = await this.getLatestVersion()
        if (localVersion === latestVersion) {
            return true
        } else {
            return false
        }
    }
    updatePackage = () => {
		return this.downloadPackage()
    }
    downloadPackage = () => {
		var name = "aikan.apk"
        const task = plus.downloader.createDownload(this.downloadUrl, {
			filename:"_downloads/"+name
		},
            (res, status) => {
                if (status === 200) {
                    plus.runtime.install(res.filename)
					return true
                }else{
					return false
				}
            })
            
        this.onProgress(task)
        task.start()
    }
    onProgress = (task) => {
        task.addEventListener('statechanged', e => {
            if (e && e.downloadedSize > 0) {
                const progress = ((e.downloadedSize / e.totalSize) * 100).toFixed(2)
                this.progress.value = progress
            }
        }, false)
    }
}
export default Upgrade